/**
 * 
 */
package ru.athena.runTool.blockTypes;

import java.sql.Connection;
import java.sql.SQLException;

import javax.swing.tree.DefaultMutableTreeNode;

import ru.athena.runTool.Model.LeafNode;

/**
 * PL/SQL Code block description
 * @author corc_usr
 *
 */
public abstract class CodeBlock {
	private String 	name_;
	private String 	text_;
	private String 	shortClassName_;
	
	/** 
	 * Construct object from text of code block 
	 * @param codeBlock - code block to store
	 */
	public CodeBlock( String codeBlock) {
		// fill name (cut first line)
		String	firstLine = codeBlock.split("\n")[0];
		int lastIndex = firstLine.length() - 1; 
		if ( firstLine.charAt( lastIndex ) == '\r' ) {
			name_ = firstLine.substring( 0, lastIndex );
		} else {
			name_ = firstLine; 
		}
		// fill value (removing \r - Oracle source restriction)
		text_ = codeBlock.replaceAll("\r", " ");

		//System.out.println(name_);

	}
	public abstract void execute( Connection conn )  throws Exception;
	
	public boolean isExecutable() {
		return false;
	};
	
	public String getShortClassName() {
		if ( shortClassName_ == null) {
			shortClassName_ = getClass().getName();
			int lastDotIndex = shortClassName_.lastIndexOf('.');
			shortClassName_ = shortClassName_.substring(++lastDotIndex);
		}
		return shortClassName_;
	}
	
	public String toString() {
		return "[" + getShortClassName() + "] " + getName();
	}

	/**
	 * @return the name of code block (first line)
	 */
	public String getName() {
		return name_;
	}

	/**
	 * @return text of code block
	 */
	public String getText() {
		return text_;
	}
	protected void setText(String text) {
		text_ = text;		
	}

	public DefaultMutableTreeNode toTreeNode() {
		return new LeafNode(this);
	}
}
